﻿$(document).ready(function () {
    validateAll();
    $ers = $('span.error, label.error');
    for(var i = 0; i < $ers.length; i++)
    {
        var selector = "#" + $($ers[i]).prev()[0].id;
        $(selector).keyup(validate);
    }
    //$('#tblCart input[type="text"]').keyup(updateQTY);
    numbericInput();
});

var delay = (function(){
  var timer = 0;
  return function(callback, ms){
    clearTimeout (timer);
    timer = setTimeout(callback, ms);
  };
})();

function updateQTY(txt)
{
    var id = txt.id.toString().replace("cartqty", "");
        
    delay(function(){
		CartFunc(id, 6);
	}, 500 );
}

function numbericInput()
{
    $('#tblCart input[type="text"], input[name*="DPhone"]').keydown(function(event) {
        // Allow only backspace and delete
        if ( event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 ) {
            // let it happen, don't do anything
        }
        else {
            // Ensure that it is a number and stop the keypress
            if ((event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105 )) {
                event.preventDefault(); 
            }   
        }
    }); 
}
function gotoLogin()
{
    $("#login_username").focus();
}

function hasValue(selector)
{
    var value = $(selector)[0].value;
    if(value.trim() == "")
        return false;
    return true;
}

function validateAll()
{
    var rs = true;
    $ers = $('span.error, label.error');
    for(var i = 0; i < $ers.length; i++)
    {
        var selector = "#" + $($ers[i]).prev()[0].id;
        
        if(!hasValue(selector))
        {
            $(selector).next().fadeIn();
            rs = false;
        }
    }
    for(var i = 0; i < $ers.length; i++)
    {
        var selector = "#" + $($ers[i]).prev()[0].id;
        
        if(!hasValue(selector))
        {
            $(selector).focus();
            break;
        }
    }
        
    return rs;
}

function validate()
{
    var selector = "#" + this.id;
    
    delay(function(){
		if(!hasValue(selector))
			$(selector).next().fadeIn();
		else
		{
		    if(selector.indexOf("DEmail") != -1)
		    {
		        var email = $(selector).val();
                var exp = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9][a-zA-Z0-9.-]*[\.]{1}[a-zA-Z]{2,4}$/;
                if(!exp.test($.trim(email)))
                    $(selector).next().fadeIn();
                else
                    $(selector).next().fadeOut();
		    }
		    else
		        $(selector).next().fadeOut();		
		}
	}, 200 );
}